//
//  HealthLearnViewController.m
//  Food
//
//  Created by dlios on 15/7/14.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "HealthLearnViewController.h"
#import "HealthKonw.h"
#import "RecommendTableViewCell.h"
#import "HeathTableViewCell.h"
#import "HealthLearnDetailsViewController.h"


@interface HealthLearnViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain) NSMutableArray *tableArr;
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) NSMutableArray *footArr;
@property (nonatomic, assign) NSInteger page;
@end

@implementation HealthLearnViewController


- (void)dealloc
{
    [super dealloc];
    [_myTableView release];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArr = [NSMutableArray array];
        self.footArr = [NSMutableArray array];
    }
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.hidesBackButton = YES;
    [self.navigationItem setLeftBarButtonItem:nil animated:NO];
    [self createSegmentControll];
    [self getData];
    [self createTableView];
    [self setupRefresh];
}

#pragma mark- 刷新加载
- (void)setupRefresh
{
// 下拉刷新
    [self.myTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
// 上拉加载
    [self.myTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    // 一进程序自动刷新
    [self.myTableView headerBeginRefreshing];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.myTableView.headerPullToRefreshText = @"下拉可以刷新了";
   self.myTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.myTableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    self.myTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.myTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.myTableView.footerRefreshingText = @"正在帮你加载中,不客气";

}

- (void)headerRereshing
{
    [self.footArr removeAllObjects];
    [AFNet connectNetGetDataWithURLString:HEAIKNOW parameters:nil finishblock:^(id result) {
        NSMutableArray *arr = [[result objectForKey:@"data"] objectForKey:@"nous"];
        for (NSDictionary *dic  in arr) {
            HealthKonw *know = [[HealthKonw alloc] initWithDic:dic];
            [self.footArr addObject:know];
            [know release];
        }
        [self.tableArr removeAllObjects];
        [self.tableArr addObjectsFromArray:self.footArr];
    }];
    

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView headerEndRefreshing];
    });
    self.page = 2;
}

- (void)footerRereshing
{
    
    NSString *str1 = @"http://api.xiangha.com/zhishi5/getNousList?page=";
    NSString *str2 =  @"&pinyin=ys&type=classify&name=健康养生";
    NSString *url = [NSString stringWithFormat:@"%@%ld%@",str1,self.page++,str2];
    
    [self.footArr removeAllObjects];
    [AFNet connectNetGetDataWithURLString:url parameters:nil finishblock:^(id result) {
        NSMutableArray *arr = [[result objectForKey:@"data"] objectForKey:@"nous"];
        for (NSDictionary *dic  in arr) {
            HealthKonw *know = [[HealthKonw alloc] initWithDic:dic];
            [self.footArr addObject:know];
            [know release];
        }
        [self.tableArr addObjectsFromArray:self.footArr];
    }];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView footerEndRefreshing];
    });
 
}
#pragma mark- 创建segmentControll
- (void)createSegmentControll
{
    
    NSArray *arr = [NSArray arrayWithObjects:@"健康",@"养生知识", nil];
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:arr];
    self.navigationItem.titleView = segment;
    segment.tintColor = [UIColor redColor];
    // 默认选中的下标
    segment.selectedSegmentIndex = 1;
    // 绑定方法
    [segment addTarget:self action:@selector(controllerPressed:) forControlEvents:UIControlEventValueChanged];
    [segment release];
}
#pragma mark- segment关联的方法

- (void)controllerPressed:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        [self.navigationController popViewControllerAnimated:NO];
    }
    
}

- (void)getData
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
    }else{

    [AFNet connectNetGetDataWithURLString:HEAIKNOW parameters:nil finishblock:^(id result) {
        NSMutableArray *arr = [[result objectForKey:@"data"] objectForKey:@"nous"];
        for (NSDictionary *dic  in arr) {
            HealthKonw *know = [[HealthKonw alloc] initWithDic:dic];
            [self.tableArr addObject:know];
            [know release];
            }
        [self.myTableView reloadData];
    }];
    
    }
}

- (void)createTableView
{
    self.myTableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64-49) style:UITableViewStylePlain] autorelease];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.myTableView registerClass:[RecommendTableViewCell class] forCellReuseIdentifier:@"cell1"];
    [self.myTableView registerClass:[HeathTableViewCell class] forCellReuseIdentifier:@"cell2"];
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    
}

#pragma mark- tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    HealthKonw *know = [self.tableArr objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        RecommendTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.know = know;
        
        return cell;
    }else{
        HeathTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell.know = know;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 160;
    }else{
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HealthLearnDetailsViewController *details = [[[HealthLearnDetailsViewController alloc] init] autorelease];
    HealthKonw *know = self.tableArr[indexPath.row];
    details.IDStr = know.IDCode;
    details.titleName = know.title;
    details.img = know.img;
    details.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:details animated:YES];
    
}

- (void)data
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
